<template>
  <div class="order">
    <van-nav-bar
      left-text="返回"
      :title="route.params.id == 2 ? '上门问诊' : '图文问诊'"
      left-arrow
      @click-left="onClickLeft"
    />

    <div class="main">
      <van-steps
        :active="0"
        class="my-card setp"
        active-icon="success"
        active-color="#38f"
      >
        <van-step>提交问题</van-step>
        <van-step>问诊咨询</van-step>
        <van-step>医生建议</van-step>
        <van-step>医生评价</van-step>
      </van-steps>
      <div class="my-card patients" @click="showSheet = true">
        <div>
          <h2>刘海</h2>
          <p><span>男</span><span>30岁</span><span>184****4893</span></p>
        </div>
        <van-icon name="arrow" size="20" />
      </div>

      <div class="my-card description" v-if="route.params.id == 2">
        <h2>我的位置</h2>
        <div id="container"></div>
      </div>

      <div class="my-card description">
        <h2>描述病情</h2>
        <van-field
          :autosize="autosize"
          placeholder="为了更好的获得医生的帮助，请尽可能详细描述您的病情。"
          type="textarea"
        />
        <h2>上传检查单/患处照片</h2>
        <van-uploader />
      </div>

      <van-submit-bar :price="1500" button-text="提交订单" @submit="toAliPay" />
    </div>

    <van-action-sheet v-model:show="showSheet" title="选择就诊人">
      <div class="content">
        <div
          v-for="index in 3"
          :key="index"
          class="my-mini-card patients"
          :class="{ select: select != index }"
          @click="select = index"
        >
          <div>
            <h3 v-if="index == 3">刘海</h3>
            <h3 v-if="index == 2">牛路</h3>
            <h3 v-if="index == 1">李明</h3>
            <p>
              <span>男</span><span>{{ index + "0岁" }}</span
              ><span>184****4893</span>
            </p>
          </div>
          <span class="edit"
            ><i style="color: #4fc08d" v-show="select == index">已选择</i
            ><i v-show="select == index">|</i
            ><van-icon @click="showPopup = true" size="21px" name="edit"
          /></span>
        </div>
        <van-button round type="primary" size="large" @click="showPop"
          >新增就诊人</van-button
        >
      </div>
    </van-action-sheet>

    <van-popup v-model:show="showPopup" position="right" class="my-popup">
      <van-nav-bar
        left-text="返回"
        title="患者信息"
        left-arrow
        @click-left="showPopup = false"
      />
      <div class="main">
        <van-form @failed="onFailed">
          <!-- 通过 pattern 进行正则校验 -->
          <van-field
            v-model="state.username"
            name="name"
            label="问诊人"
            placeholder="请输入问诊人姓名"
            :rules="[{ required: true, message: '请输入问诊人姓名' }]"
          />
          <van-field name="sex" label="性别">
            <template #input>
              <van-radio-group v-model="state.sex" direction="horizontal">
                <van-radio name="1">男</van-radio>
                <van-radio name="2">女</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
            v-model="state.birth"
            readonly
            clickable
            name="birth"
            label="出生日期"
            placeholder="点击选择日期"
            :rules="[{ required: true, message: '请输入选择出生日期' }]"
            @click="showCalendar = true"
          />
          <van-field
            placeholder="请输入手机号"
            v-model="state.tel"
            name="tel"
            type="tel"
            label="手机号"
            :rules="[{ required: true, message: '请输入输入手机号' }]"
          />
          <van-field
            v-model="state.local"
            readonly
            clickable
            name="area"
            label="地区选择"
            placeholder="点击选择省市区"
            @click="state.showArea = true"
          />
          <van-field
            placeholder="请输入病例信息"
            v-model="state.medicalHistory"
            name="medicalHistory"
            type="textarea"
            rows="4"
            show-word-limit
            label="病例信息"
            maxlength="50"
            :rules="[{ required: true, message: '请输入病例信息' }]"
          />
          <div style="margin: 16px">
            <van-button round block type="primary" native-type="submit">
              保存
            </van-button>
          </div>
        </van-form>
      </div>
      <van-calendar v-model:show="showCalendar" @confirm="onConfirm" />
      <van-popup v-model:show="state.showArea" position="bottom">
        <van-cascader
          v-model="state.local"
          title="请选择所在地区"
          :options="state.options"
          @close="state.showArea = false"
          @change="onChange"
          @finish="onFinish"
          :field-names="fieldNames"
        />
      </van-popup>
    </van-popup>
  </div>
</template>

<script>
import { reactive, ref, onMounted } from "vue";
import { Loading, Toast } from "vant";
import { useRouter, useRoute } from "vue-router";
import { getCity, toPay } from "../api/user";

export default {
  name: "OrderInfo",
  setup() {
    const showSheet = ref(false);
    const showPopup = ref(false);
    const showCalendar = ref(false);
    const showArea = ref(false);
    const select = ref(1);
    const autosize = reactive({
      maxHeight: 400,
      minHeight: 200,
    });
    //实例化路由
    const router = useRouter();
    const route = useRoute();
    const onClickLeft = () => {
      router.go(-1);
    };

    //级联选择器自定义字段
    const fieldNames = {
      text: "name",
      value: "id",
      children: "children",
    };

    const state = reactive({
      name: "", //姓名
      sex: "1", //性别
      birth: "", //出生日期
      local: "", //位置
      tel: "", //手机号
      medicalHistory: "", //病史
      options: [],
    });

    //监听完成
    const onFinish = ({ selectedOptions }) => {
      if (selectedOptions.length == 4) {
        state.showArea = false;
        console.log(selectedOptions);
        state.local = selectedOptions[3].fullname;
      }
    };

    //监听选择
    const onChange = ({ value, selectedOptions, tabIndex }) => {
      if (tabIndex == 0) {
        getCity(value).then((res) => {
          //遍历一级节点
          for (let i = 0; i < state.options.length; i++) {
            //找到刚才选择的一级节点
            if (state.options[i].id == value) {
              //将查询结果挂在到 一级节点上
              state.options[i].children = res.data.data;
              break;
            }
          }
        });
      }
      if (tabIndex == 1) {
        getCity(value).then((res) => {
          //遍历一级节点
          for (let i = 0; i < state.options.length; i++) {
            //找到刚才选择的一级节点
            if (state.options[i].id == selectedOptions[0].id) {
              //遍历二级节点
              for (let j = 0; j < state.options[i].children.length; j++) {
                //找到已经选择的二级节点
                if (state.options[i].children[j].id == value) {
                  //将查询结果挂在到 二级节点上
                  state.options[i].children[j].children = res.data.data;
                }
              }
              break;
            }
          }
        });
      }
      if (tabIndex == 2) {
        getCity(value).then((res) => {
          //遍历一级节点
          for (let i = 0; i < state.options.length; i++) {
            //找到刚才选择的一级节点
            if (state.options[i].id == selectedOptions[0].id) {
              //遍历二级节点
              for (let j = 0; j < state.options[i].children.length; j++) {
                //找到已经选择的二级节点
                if (state.options[i].children[j].id == selectedOptions[1].id) {
                  //遍历三级节点
                  for (
                    let k = 0;
                    k < state.options[i].children[j].children.length;
                    k++
                  ) {
                    //找到已经选择的三级节点
                    if (state.options[i].children[j].children[k].id == value) {
                      //将查询结果挂在到 三级节点上
                      state.options[i].children[j].children[k].children =
                        res.data.data;
                      break;
                    }
                  }
                  break;
                }
              }
              break;
            }
          }
        });
      }
    };

    //表单校验 失败
    const onFailed = (errorInfo) => {
      console.log("failed", errorInfo);
    };
    //日历选择
    const onConfirm = (date) => {
      console.log(date);
      state.birth = `${date.getFullYear()}/${
        date.getMonth() + 1
      }/${date.getDate()}`;
      showCalendar.value = false;
    };
    //打开新增面板
    const showPop = () => {
      showPopup.value = true;

      getCity(-1).then((res) => {
        state.options = res.data.data;
      });
    };

    //去支付 toPay
    const toAliPay = () => {
      let userInfo = JSON.parse(localStorage.getItem("userInfo"));
      toPay(userInfo.userId, "1392460821400301569").then((res) => {
        localStorage.setItem("aliPayHtml", res.data);
        router.push("/aliPay");
      });
    };
    onMounted(() => {
      console.log("mounted!");
      if (route.params.id == 2) {
        loadingMap();
      }
    });

    const loadingMap = () => {
      //初始化地图对象，加载地图
      var map = new AMap.Map("container", {
        resizeEnable: true,
        zoom: 15,
        mapStyle: "amap://styles/ef4043186fb1023712c99ed92e59a669", //设置地图的显示样式
      });
      var options = {
        showButton: true, //是否显示定位按钮
        buttonPosition: "LB", //定位按钮的位置
        /* LT LB RT RB */
        buttonOffset: new AMap.Pixel(10, 20), //定位按钮距离对应角落的距离
        showMarker: true, //是否显示定位点
        markerOptions: {
          //自定义定位点样式，同Marker的Options
          offset: new AMap.Pixel(-18, -36),
          content:
            '<img src="https://a.amap.com/jsapi_demos/static/resource/img/user.png" style="width:36px;height:36px"/>',
        },
        showCircle: true, //是否显示定位精度圈
        circleOptions: {
          //定位精度圈的样式
          strokeColor: "#0093FF",
          noSelect: true,
          strokeOpacity: 0.5,
          strokeWeight: 1,
          fillColor: "#02B0FF",
          fillOpacity: 0.25,
        },
      };
      AMap.plugin(["AMap.Geolocation"], () => {
        var geolocation = new AMap.Geolocation(options);
        map.addControl(geolocation);
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, "complete", onComplete);

        function onComplete(data) {
          // data是具体的定位信息
          console.log(data);
        }
      });
    };
    return {
      fieldNames,
      showPop,
      showArea,
      onClickLeft,
      state,
      showSheet,
      select,
      autosize,
      showPopup,
      onFailed,
      showCalendar,
      onConfirm,
      onFinish,
      onChange,
      toAliPay,
      route,
    };
  },
};
</script>

<style>
.order {
  background: #f7f8fa;
}
.content {
  padding: 16px 16px 16px;
}
.main {
  padding: 10px;
  padding-bottom: 50px;
}
.setp {
  margin-bottom: 24px;
}
.my-card {
  margin-bottom: 24px;
  padding: 24px;
  background-color: #fff;
  border-radius: 20px;
  box-shadow: 0 8px 12px #ebedf0;
}
.my-mini-card {
  margin-bottom: 10px;
  padding: 10px;
  background-color: #fff;
  border-radius: 20px;
  box-shadow: 0 8px 12px #ebedf0;
}
.patients {
  text-align: left;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.patients h3 {
  margin: 0;
  padding: 0;
}
.my-mini-card {
  padding-left: 20px;
}
.my-mini-card p {
  margin: 0;
  margin-top: 2px;
  padding: 0;
}
.patients p span {
  color: #969799;
  margin-right: 10px;
}
.my-mini-card .edit {
  display: flex;
}
.my-mini-card .edit i {
  margin-right: 10px;
}
.content .select {
  background-color: #ebfff0;
}

.description .van-field__control {
  background: #f7f7f7;
  border: #e0e0e0 solid 1px;
  padding: 10px;
  border-radius: 5px;
}
.description {
  text-align: left;
}
.description h2 {
  margin-bottom: 20px;
}
.description .van-cell {
  padding: 0;
}
.my-popup {
  height: 100%;
  width: 100%;
}
.my-popup .save {
  padding: 20px;
}
#container {
  width: 300px;
  height: 180px;
}
</style>